<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class MakerService extends BaseService
{
    //首页

    /**
     * 选项
     */
    public function getOption()
    {
        $arys = ['item' => [], 'front' => [], 'back' => [], 'font' => []];
        //项目选项
        $arys['item'] = DB::table($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 1)
            ->get();
        //前端选项
        $arys['front'] = DB::table($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 2)
            ->get();
        //后端选项
        $arys['back'] = DB::table($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 3)
            ->get();
        //字体选项
        $arys['font'] = DB::table($this->dbMkConfig)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('type', 4)
            ->get();
        return $this->toback(0, '', $arys);
    }

    //创建项目
    public function addItem($uid, $pas)
    {
        //验证项目类型
        $res = (array) $this->dbConn($this->dbMkConfig)
            ->where('del', 0)
            ->where('type', 1)
            ->where('id', $pas['type'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '项目类型不存在');
        }
        //验证项目前端技术栈
        $res = (array) $this->dbConn($this->dbMkConfig)
            ->where('del', 0)
            ->where('type', 2)
            ->where('id', $pas['front'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '项目前端技术栈不存在');
        }
        //验证项目后端技术栈
        $res = (array) $this->dbConn($this->dbMkConfig)
            ->where('del', 0)
            ->where('type', 3)
            ->where('id', $pas['back'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '项目后端技术栈不存在');
        }
        //验证项目字体
        $res = (array) $this->dbConn($this->dbMkConfig)
            ->where('del', 0)
            ->where('type', 4)
            ->where('id', $pas['font'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '项目字体不存在');
        }
        $en = toItemName();
        $iData = [
            'uid' => $uid,
            'cn' => $pas['cn'],
            'en' => $en,
            'type' => $pas['type'],
            'front' => $pas['front'],
            'back' => $pas['back'],
            'font' => $pas['font'],
            'addtime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbMkItem)->insertGetId($iData);
        if (!$lastid) {
            return $this->toback(-1, '创建失败');
        }
        //返回数据
        $resData = [
            'item_id' => $lastid,
            'item_name' => $pas['cn'],
            'serial' => $en,
            'treelist' => $this->treelist($lastid),
        ];
        return $this->toback(0, '', $resData);
    }

    //获取项目树
    public function treelist($uid, $itemid)
    {
        $treelist = [ //代码树
            [
                'id' => 0, //文件ID
                'title' => '前端代码', //文件名
                'detail' => '0', //文件内容
                'childList' => [
                ]
            ],
            [
                'id' => 0, //文件ID
                'title' => '后端代码', //文件名
                'detail' => '0', //文件内容
                'childList' => [
                ]
            ]
        ];
        $itemOne = (array) $this->dbConn($this->dbMkItem)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('id', $itemid)
            ->first();
        if (empty($itemOne)) {
            return $treelist;
        }
        return $treelist;
    }

    //获取项目
    public function itemOne($id)
    {
        return (array) $this->dbConn($this->dbMkItem)
            ->where('del', 0)->where('id', $id)
            ->first();
    }

    //保存图片
    public function addImg($token, $imglink)
    {
        $uid = $this->getUidByToken($token);
        if (!$uid) {
            return $this->toback(-2, '没有登录');
        }
        $id = $this->dbInsertOne($this->dbMkUpload, [
            'uid' => $uid, 'link' => $imglink,
            'addtime' => toDate(),
        ]);
        if (!$id) {
            return $this->toback(-1, '保存失败');
        }
        return $this->toback(0, '', $id);
    }

    //获取图片
    public function getImgOne($id)
    {
        $resOne = $this->dbQueryOne($this->dbMkUpload, ['id' => $id]);
        if (empty($resOne)) {
            return $this->toback(-2, '没有图片');
        }
        $resOne['link'] = env('DOMAIN') . '/' . $resOne['link'];
        return $this->toback(0, '', $resOne);
    }

    //保存文字信息
    public function modifyImg($id, $words)
    {
        if (empty($words)) {
            return $this->toback(-2, '没有词汇');
        }
        $strs = [];
        foreach ($words as $v) {
            if (isset($v['words']) && $v['words']) {
                $strs[] = $v['words'];
            }
        }
        $strs = implode('||||', $strs);
        $up = $this->dbModify($this->dbMkUpload, ['id' => $id], ['words' => $strs, 'uptime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, '保存信息失败');
        }
        return $this->toback(0, '', $strs);
    }

    /**
     * 保存功能
     * @param int $uid
     * @param int $item_id 项目ID
     * @param int $words 功能描述
     */
    public function addWord($uid, $item_id, $words)
    {
        //找出匹配的功能
        $funOne = (array) $this->dbConn($this->dbMkWord)
            ->where('del', 0)
            ->where('pid', 0)
            ->whereIn('cn', $words)
            ->orderBy('id', 'asc')
            ->first();
        if (empty($funOne)) {
            return $this->toback(-2, '无有效功能');
        }
        //添加功能
        $uData = [
            'item_id' => $item_id,
            'uid' => $uid,
            'word_id' => $funOne['id'],
            'cn' => $funOne['cn'],
            'en' => $funOne['en'],
            'addtime' => toDate(),
        ];
        $pid = $this->dbConn($this->dbMkUser)->insertGetId($uData);
        //添加字段
        $childOnes = $this->dbConn($this->dbMkWord)
            ->where('del', 0)
            ->where('pid', $funOne['id'])
            ->whereIn('cn', $words)
            ->get();
        if (count($childOnes)) {
            foreach ($childOnes as $vv) {
                $vv = (array) $vv;
                $u2Data = [
                    'item_id' => $item_id,
                    'uid' => $uid,
                    'word_id' => $vv['id'],
                    'cn' => $vv['cn'],
                    'en' => $vv['en'],
                    'pid' => $pid,
                    'addtime' => toDate(),
                ];
                $this->dbConn($this->dbMkUser)->insertGetId($u2Data);
            }
        }
        //将入库的功能返回
        $resData = $this->getUserFunOne($pid);
        return $this->toback(0, '', $resData);
    }

    //通过ID获取用户功能
    public function getUserFunOne($id)
    {
        $funOne = (array) $this->dbConn($this->dbMkUser)
            ->where('pid', 0)
            ->where('id', $id)
            ->first();
        if (empty($funOne)) {
            return [];
        }
        $childList = [];
        $fieldOnes = $this->dbConn($this->dbMkUser)
            ->where('pid', $funOne['id'])
            ->get();
        if (count($fieldOnes)) {
            foreach ($fieldOnes as $vv) {
                $vv = (array) $vv;
                $childList[] = [
                    'id' => $vv['id'],
                    'cn' => $vv['cn'],
                    'en' => $vv['en'],
                ];
            }
        }
        $arys = [
            'id' => $funOne['id'],
            'cn' => $funOne['cn'],
            'en' => $funOne['en'],
            'fieldList' => $childList,
        ];
        return $arys;
    }

    /**
     * 生成前端文件
     * @param int $uid 用户UID
     * @param int $itemid 项目ID
     * @param int $funid 功能ID
     */
    public function mkFront($uid, $itemid, $funid)
    {
        //看看项目有没有
        $itemOne = $this->itemOne($itemid);
        if (empty($itemOne)) {
            return $this->toback(-2, '没有功能');
        }
        //看看功能有没有
        $funOne = $this->getUserFunOne($funid);
        if (empty($funOne)) {
            return $this->toback(-2, '没有功能');
        }
        $prefix = 'ai_items/'.$itemOne['en'].'/';
        if(!file_exists($prefix)){ mkdir($prefix, 0777); }
        $prefix = 'ai_items/'.$itemOne['en'].'/front/';
        if(!file_exists($prefix)){ mkdir($prefix, 0777); }
        $fpath = $prefix . $funOne['en'] . '.html';
        $html = '';
        //头部代码
        $html .= "<!DOCTYPE HTML>\n";
        $html .= "<html>\n";
        $html .= "<head>\n";
        $html .= "<meta charset=\"utf-8\"/>\n";
        $html .= "<meta name=\"renderer\" content=\"webkit|ie-comp|ie-stand\"/>\n";
        $html .= "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"/>\n";
        $html .= "meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"/>\n";
        $html .= "<title>用户页面</title>\n";
        $html .= "<style type=\"text/css\"></style>\n";
//        $html .= `
//<!DOCTYPE HTML>
//<html>
//<head>
//	<meta charset="utf-8">
//	<meta name="renderer" content="webkit|ie-comp|ie-stand">
//	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
//	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
//	<title>用户页面</title>
//	<style type="text/css">
//	</style>
//</head>
//<body>
//`;
//        //底部代码
//        $html .= `
//</body>
//</html>
//<script type="text/javascript">
//</script>
//        `;
        file_put_contents($fpath, $html);
        $arys = [
            'fname' => $funOne['en'],
            'fpath' => $fpath,
        ];
        return $this->toback(0, '', $arys);
    }
}